document.addEventListener('DOMContentLoaded', function() {
  const searchInput = document.getElementById('searchInput');
  const bookmarksList = document.getElementById('bookmarksList');
  const previewFrame = document.getElementById('previewFrame');
  const loadingIndicator = document.querySelector('.loading-indicator');
  const previewContainer = document.querySelector('.preview-container');
  const qrcodeButton = document.getElementById('qrcodeButton');
  const qrcodePopup = document.getElementById('qrcodePopup');
  const qrcodeContainer = document.getElementById('qrcodeContainer');
  const aiSearchToggle = document.getElementById('aiSearchToggle');
  const refreshButton = document.getElementById('refreshButton');
  const openInNewButton = document.getElementById('openInNewButton');
  let previewTimeout = null;
  let lastUrl = '';
  // 添加全局URL加载方式缓存
  const loadMethodCache = new Map();
  // 添加当前加载控制器
  let currentController = null;
  // 添加防抖计时器
  let previewDebounceTimer = null;
  // 添加当前激活的书签项
  let activeBookmarkItem = null;
  // 添加最后请求的URL
  let lastRequestedUrl = '';
  // 添加预览状态标志
  let isPreviewActive = false;

  // 绑定工具栏按钮事件
  refreshButton.addEventListener('click', function(e) {
    e.preventDefault();
    e.stopPropagation();
    console.log('Refresh button clicked');
    if (previewFrame.src && previewFrame.src !== 'about:blank') {
      // 重新加载预览内容
      previewFrame.src = previewFrame.src;
      // 添加刷新动画
      this.classList.add('refreshing');
      setTimeout(() => {
        this.classList.remove('refreshing');
      }, 500);
    }
  });

  openInNewButton.addEventListener('click', function(e) {
    e.preventDefault();
    e.stopPropagation();
    console.log('Open in new tab button clicked');
    if (previewFrame.src && previewFrame.src !== 'about:blank') {
      chrome.tabs.create({
        url: previewFrame.src,
        active: true
      });
    }
  });

  qrcodeButton.addEventListener('mouseenter', function(e) {
    e.preventDefault();
    e.stopPropagation();
    console.log('QR code button mouseenter');
    if (previewFrame.src && previewFrame.src !== 'about:blank') {
      generateQRCode(previewFrame.src);
      qrcodePopup.classList.add('show');
    }
  });

  qrcodeButton.addEventListener('mouseleave', function(e) {
    e.preventDefault();
    e.stopPropagation();
    console.log('QR code button mouseleave');
    qrcodePopup.classList.remove('show');
  });

  // 加载AI搜索开关状态
  chrome.storage.sync.get(['aiSearchEnabled', 'qwenApiKey'], function(result) {
    if (result.aiSearchEnabled) {
      aiSearchToggle.checked = true;
    }
    // 如果没有API Key但开关是开启状态，则关闭开关
    if (!result.qwenApiKey && aiSearchToggle.checked) {
      aiSearchToggle.checked = false;
      showAiSearchError('请先在插件的扩展程序选项中配置模型和API Key');
    }
  });

  // 监听AI搜索开关变化
  aiSearchToggle.addEventListener('change', function() {
    if (this.checked) {
      // 检查是否已配置API Key
      chrome.storage.sync.get(['qwenApiKey'], function(result) {
        if (!result.qwenApiKey) {
          aiSearchToggle.checked = false;
          showAiSearchError('请先在插件的扩展程序选项中配置模型和API Key');
          return;
        }
        // 如果有API Key，保存开关状态并执行搜索
        chrome.storage.sync.set({ aiSearchEnabled: true }, function() {
          // 如果当前有搜索词，执行AI搜索
          const currentQuery = searchInput.value.trim();
          if (currentQuery) {
            // 先清除现有的AI结果
            clearAiResults();
            // 获取所有书签并执行AI搜索
            chrome.bookmarks.getTree(async function(bookmarkTreeNodes) {
              function extractBookmarks(nodes) {
                let bookmarks = [];
                for (const node of nodes) {
                  if (node.url) {
                    bookmarks.push(node);
                  }
                  if (node.children) {
                    bookmarks = bookmarks.concat(extractBookmarks(node.children));
                  }
                }
                return bookmarks;
              }

              const allBookmarks = extractBookmarks(bookmarkTreeNodes);
              if (allBookmarks.length > 0) {
                showAiSearchStatus();
                const semanticResults = await semanticSearchBookmarks(currentQuery, allBookmarks);
                hideAiSearchStatus();
                
                if (semanticResults.length > 0) {
                  // 获取当前显示的所有URL
                  const existingUrls = new Set(
                    Array.from(bookmarksList.querySelectorAll('.bookmark-item'))
                      .map(item => item.dataset.url)
                  );

                  // 过滤掉重复的结果
                  const uniqueResults = semanticResults.filter(
                    result => !existingUrls.has(result.url)
                  );

                  if (uniqueResults.length > 0) {
                    // 更新结果数量
                    const currentBookmarks = document.querySelectorAll('.bookmark-item').length;
                    const resultsCount = document.querySelector('.search-results-count');
                    resultsCount.textContent = `找到 ${currentBookmarks + uniqueResults.length} 个相关书签`;
                    // 渲染未重复的结果
                    renderBookmarks(uniqueResults, true);
                  }
                }
              }
            });
          }
        });
      });
    } else {
      // 关闭AI搜索，保存状态并清除AI搜索结果
      chrome.storage.sync.set({ aiSearchEnabled: false });
      clearAiResults();
      if (searchInput.value.trim()) {
        searchBookmarks(searchInput.value);
      }
    }
  });

  // 显示AI搜索错误信息
  function showAiSearchError(message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'ai-search-error';
    errorDiv.textContent = message;
    errorDiv.style.cssText = `
      position: absolute;
      top: 100%;
      right: 0;
      background: #fce8e6;
      color: #c5221f;
      padding: 8px 12px;
      border-radius: 4px;
      font-size: 12px;
      z-index: 1000;
      margin-top: 4px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    `;
    
    // 移除之前的错误提示
    const existingError = document.querySelector('.ai-search-error');
    if (existingError) {
      existingError.remove();
    }
    
    document.querySelector('.search-wrapper').appendChild(errorDiv);
    
    // 3秒后自动消失
    setTimeout(() => {
      errorDiv.remove();
    }, 3000);
  }

  // 清除AI搜索结果
  function clearAiResults() {
    const aiResults = document.querySelectorAll('.bookmark-item.ai-result');
    aiResults.forEach(result => result.remove());
    updateResultsCount();
  }

  // 更新搜索结果数量显示
  function updateResultsCount() {
    const resultsCount = document.querySelector('.search-results-count');
    const totalResults = document.querySelectorAll('.bookmark-item').length;
    const query = searchInput.value.trim();
    resultsCount.textContent = query 
      ? `找到 ${totalResults} 个相关书签` 
      : `共有 ${totalResults} 个书签`;
  }

  // 加载本地QRCode库
  const script = document.createElement('script');
  script.src = 'qrcode.min.js';
  document.head.appendChild(script);

  // QR码相关功能
  let qrcodeInstance = null;

  function generateQRCode(url) {
    if (!window.QRCode) return; // 如果QRCode库还没加载完成，直接返回
    
    // 清除之前的二维码
    qrcodeContainer.innerHTML = '';
    
    // 生成新的二维码
    qrcodeInstance = new QRCode(qrcodeContainer, {
      text: url,
      width: 128,
      height: 128,
      colorDark: "#000000",
      colorLight: "#ffffff",
      correctLevel: QRCode.CorrectLevel.H,
      useSVG: true // 使用SVG以获得更好的渲染质量
    });
  }

  // 确保QRCode库加载完成
  script.onload = () => {
    console.log('QRCode库加载完成');
  };

  script.onerror = () => {
    console.error('QRCode库加载失败');
  };

  // 添加favicon缓存
  const faviconCache = new Map();
  const faviconImageCache = new Map();

  // 获取favicon的函数
  function getFaviconUrl(bookmark) {
    const url = bookmark.url;
    if (faviconCache.has(url)) {
      return faviconCache.get(url);
    }
    
    // 尝试使用Google的favicon服务作为备选
    const googleFaviconUrl = `https://www.google.com/s2/favicons?domain=${encodeURIComponent(new URL(url).hostname)}&sz=32`;
    const chromeFaviconUrl = `chrome-extension://${chrome.runtime.id}/_favicon/?pageUrl=${encodeURIComponent(url)}&size=16`;
    
    // 默认使用Chrome的favicon服务
    faviconCache.set(url, chromeFaviconUrl);
    return chromeFaviconUrl;
  }

  // 预加载favicon
  function preloadFavicon(bookmark) {
    const url = bookmark.url;
    if (faviconImageCache.has(url)) {
      return faviconImageCache.get(url);
    }

    const img = new Image();
    img.className = 'bookmark-favicon';
    
    // 创建一个Promise来处理图片加载
    const loadImage = (src) => {
      return new Promise((resolve, reject) => {
        img.onload = () => resolve(img);
        img.onerror = reject;
        img.src = src;
      });
    };

    // 尝试加载Chrome的favicon
    const chromeFaviconUrl = getFaviconUrl(bookmark);
    loadImage(chromeFaviconUrl)
      .catch(() => {
        // 如果Chrome的favicon加载失败，尝试Google的favicon服务
        const googleFaviconUrl = `https://www.google.com/s2/favicons?domain=${encodeURIComponent(new URL(bookmark.url).hostname)}&sz=32`;
        return loadImage(googleFaviconUrl);
      })
      .catch(() => {
        // 如果两个服务都失败，使用默认图标
        img.src = 'images/default-favicon.png';
      })
      .finally(() => {
        // 无论成功失败，都缓存结果
        faviconImageCache.set(url, img);
      });

    return img;
  }

  // 修改handlePreview函数
  async function handlePreview(url) {
    if (url === lastRequestedUrl) return;
    lastRequestedUrl = url;

    // 立即显示工具栏
    previewContainer.classList.add('previewing');
    isPreviewActive = true;
    previewFrame.classList.remove('loaded');

    // 取消之前的请求
    if (currentController) {
      currentController.abort();
    }

    // 创建新的AbortController
    currentController = new AbortController();

    try {
      // 显示加载指示器
      loadingIndicator.classList.add('show');
      
      // 直接设置iframe的src
      previewFrame.src = url;
      
      // 监听iframe加载完成
      previewFrame.onload = () => {
        // 隐藏加载指示器
        loadingIndicator.classList.remove('show');
        // 显示iframe内容
        previewFrame.classList.add('loaded');
        // 更新最后加载的URL
        lastUrl = url;
      };
      
      // 监听iframe加载失败
      previewFrame.onerror = () => {
        console.error('Failed to load preview:', url);
        loadingIndicator.classList.remove('show');
      };
      
    } catch (error) {
      if (error.name === 'AbortError') {
        console.log('Preview request aborted');
      } else {
        console.error('Preview error:', error);
      }
      loadingIndicator.classList.remove('show');
    }
  }

  // 修改closePreview函数
  function closePreview() {
    if (previewFrame) {
      previewFrame.src = 'about:blank';
      previewFrame.classList.remove('loaded');
    }
    if (previewContainer) {
      previewContainer.classList.remove('previewing');
    }
    if (loadingIndicator) {
      loadingIndicator.classList.remove('show');
    }
    isPreviewActive = false;
    lastRequestedUrl = '';
  }

  // 通过fetch获取并渲染页面内容
  async function fetchAndRenderContent(url, signal) {
    try {
      // 检查是否仍是最新请求
      if (lastRequestedUrl !== url) {
        return;
      }

      const response = await fetch(url, { signal });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const html = await response.text();
      
      // 如果请求已经被取消或不是最新请求，直接返回
      if (signal.aborted || lastRequestedUrl !== url) {
        return;
      }

      // 使用DOMParser解析HTML
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      
      // 获取基础URL
      const baseUrl = new URL(url);
      
      // 优化处理相对路径的函数
      const processRelativePaths = (elements, attribute) => {
        elements.forEach(el => {
          const attrValue = el.getAttribute(attribute);
          if (attrValue && !attrValue.startsWith('http') && !attrValue.startsWith('data:')) {
            el.setAttribute(attribute, new URL(attrValue, baseUrl).href);
          }
        });
      };
      
      // 并行处理所有资源路径
      processRelativePaths(doc.querySelectorAll('img'), 'src');
      processRelativePaths(doc.querySelectorAll('link[rel="stylesheet"]'), 'href');
      processRelativePaths(doc.querySelectorAll('script'), 'src');
      
      // 添加基础样式
      const styleTag = doc.createElement('style');
      styleTag.textContent = `
        body { 
          margin: 0; 
          padding: 0; 
          font-family: system-ui, -apple-system, sans-serif;
          overflow-x: hidden;
        }
        img { 
          max-width: 100%; 
          height: auto; 
        }
        /* 禁用所有脚本执行 */
        script {
          display: none !important;
        }
      `;
      doc.head.appendChild(styleTag);

      // 移除所有script标签
      doc.querySelectorAll('script').forEach(script => script.remove());
      
      // 如果请求已经被取消或不是最新请求，直接返回
      if (signal.aborted || lastRequestedUrl !== url) {
        return;
      }

      // 直接更新UI状态，不等待iframe加载
      loadingIndicator.classList.remove('show');
      previewFrame.classList.add('loaded');
      previewContainer.classList.add('previewing');

      // 设置内容
      previewFrame.srcdoc = doc.documentElement.outerHTML;

      // 监听iframe加载完成，用于处理可能的错误
      previewFrame.onload = () => {
        if (signal.aborted || lastRequestedUrl !== url) return;

        // 检查内容是否正确加载
        try {
          const iframeDoc = previewFrame.contentDocument;
          if (!iframeDoc || !iframeDoc.body.innerHTML.trim()) {
            throw new Error('内容为空');
          }
        } catch (error) {
          console.warn('iframe内容检查失败:', error);
          // 即使检查失败也保持内容显示，因为可能是跨域限制导致
        }
      };

      // 处理加载错误
      previewFrame.onerror = () => {
        if (signal.aborted || lastRequestedUrl !== url) return;
        console.warn('iframe加载出现错误，但内容可能已经显示');
      };
      
    } catch (error) {
      if (!signal.aborted && lastRequestedUrl === url) {
        console.error('Failed to fetch and render content:', error);
        // 显示错误信息
        previewFrame.srcdoc = `
          <div style="display:flex;justify-content:center;align-items:center;height:100%;font-family:Arial;color:#666;">
            <div style="text-align:center">
              <div style="font-size:48px;margin-bottom:10px">😕</div>
              <div>页面加载失败</div>
              <div style="font-size:12px;color:#999;margin-top:8px">原因：${error.message}</div>
            </div>
          </div>
        `;
        // 确保更新UI状态
        loadingIndicator.classList.remove('show');
        previewFrame.classList.add('loaded');
        previewContainer.classList.add('previewing');
      }
    }
  }

  // 保存当前状态
  function saveState() {
    const state = {
      lastSearch: searchInput.value,
      lastPreview: previewFrame.src,
      activeBookmark: document.querySelector('.bookmark-item.active')?.dataset.url,
      lastAiResults: Array.from(document.querySelectorAll('.bookmark-item.ai-result')).map(item => ({
        url: item.dataset.url,
        title: item.querySelector('.bookmark-title').textContent,
        isAiResult: true
      }))
    };
    chrome.storage.local.set(state);
  }

  // 恢复上次的状态
  function restoreState() {
    chrome.storage.local.get([
      'lastSearch', 
      'lastPreview', 
      'activeBookmark', 
      'lastAiResults'
    ], (result) => {
      if (result.lastSearch?.trim()) {
        searchInput.value = result.lastSearch;
        // 先执行常规搜索
        chrome.bookmarks.search(result.lastSearch, function(results) {
          const filteredResults = results.filter(bookmark => bookmark.url);
          renderBookmarks(filteredResults);
          
          // 然后恢复AI搜索结果
          if (result.lastAiResults && result.lastAiResults.length > 0) {
            renderBookmarks(result.lastAiResults, true);
            // 更新总结果计数
            const totalResults = document.querySelectorAll('.bookmark-item').length;
            const resultsCount = document.querySelector('.search-results-count');
            resultsCount.textContent = `找到 ${totalResults} 个相关书签`;
          }
          
          // 恢复激活的书签项
          if (result.activeBookmark) {
            const bookmarkItems = document.querySelectorAll('.bookmark-item');
            const activeItem = Array.from(bookmarkItems).find(item => 
              item.dataset.url === result.activeBookmark
            );
            if (activeItem) {
              activeBookmarkItem = activeItem;
              activeItem.classList.add('active');
              if (result.lastPreview) {
                handlePreview(result.lastPreview);
              }
            }
          }
        });
      } else {
        // 搜索内容为空时，清空结果列表并显示提示
        bookmarksList.innerHTML = '';
        const resultsCount = document.querySelector('.search-results-count');
        resultsCount.textContent = '请输入关键词搜索书签';
      }
    });
  }

  // 搜索书签
  function searchBookmarks(query, isAiSearch = false) {
    if (!query?.trim()) {
      bookmarksList.innerHTML = '';
      const resultsCount = document.querySelector('.search-results-count');
      resultsCount.textContent = '请输入关键词搜索书签';
      return;
    }

    // 清空之前的搜索结果，但保留AI搜索状态元素
    const aiSearchStatus = bookmarksList.querySelector('.ai-search-status');
    bookmarksList.innerHTML = '';
    if (aiSearchStatus) {
      bookmarksList.appendChild(aiSearchStatus);
    }

    // 存储已显示的URL，用于去重
    const displayedUrls = new Set();

    chrome.bookmarks.search(query, function(results) {
      const filteredResults = results.filter(bookmark => bookmark.url);
      
      // 记录已显示的URL
      filteredResults.forEach(bookmark => {
        displayedUrls.add(bookmark.url);
      });
      
      renderBookmarks(filteredResults);
      
      const resultsCount = document.querySelector('.search-results-count');
      resultsCount.textContent = `找到 ${filteredResults.length} 个相关书签`;

      // 如果不是AI搜索请求，保存当前状态
      if (!isAiSearch) {
        saveState();
      }

      // 如果是AI搜索请求且AI搜索开启，执行语义搜索
      if (isAiSearch && aiSearchToggle.checked) {
        chrome.storage.sync.get(['qwenApiKey'], function(result) {
          if (result.qwenApiKey) {
            showAiSearchStatus();
            // 获取所有书签用于AI搜索
            chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
              function extractBookmarks(nodes) {
                let bookmarks = [];
                for (const node of nodes) {
                  if (node.url) {
                    bookmarks.push(node);
                  }
                  if (node.children) {
                    bookmarks = bookmarks.concat(extractBookmarks(node.children));
                  }
                }
                return bookmarks;
              }
              
              const allBookmarks = extractBookmarks(bookmarkTreeNodes);
              semanticSearchBookmarks(query, allBookmarks).then(aiResults => {
                if (aiResults && aiResults.length > 0) {
                  // 过滤掉已显示的URL
                  const uniqueAiResults = aiResults.filter(bookmark => !displayedUrls.has(bookmark.url));
                  if (uniqueAiResults.length > 0) {
                    renderBookmarks(uniqueAiResults, true);
                    // 更新结果计数，包含AI结果
                    const totalResults = document.querySelectorAll('.bookmark-item').length;
                    const resultsCount = document.querySelector('.search-results-count');
                    resultsCount.textContent = `找到 ${totalResults} 个相关书签`;
                  }
                }
                hideAiSearchStatus();
                // AI搜索完成后保存状态
                saveState();
              }).catch(error => {
                console.error('AI搜索失败:', error);
                hideAiSearchStatus();
                // 即使AI搜索失败也保存状态
                saveState();
              });
            });
          }
        });
      }
    });
  }

  // 语义搜索书签
  async function semanticSearchBookmarks(query, bookmarks) {
    try {
      // 检查参数是否有效
      if (!query?.trim() || !bookmarks?.length) {
        console.log('无效的搜索参数，跳过AI搜索');
        return [];
      }

      // 获取API Key和模型设置
      const result = await chrome.storage.sync.get(['qwenApiKey', 'qwenModel', 'aiSearchEnabled']);
      const apiKey = result.qwenApiKey;
      const model = result.qwenModel || 'qwen-turbo'; // 默认使用turbo模型
      
      // 检查是否启用了AI检索
      if (!result.aiSearchEnabled) {
        console.log('AI检索未启用');
        return [];
      }
      
      if (!apiKey) {
        console.log('未设置API Key');
        return [];
      }

      // 构建提示词
      const prompt = `作为一个书签搜索助手，请帮我从以下书签列表中找出与查询"${query}"最相关的书签。

书签列表：
${bookmarks.map(b => `- ${b.title || b.url}`).join('\n')}

要求：
1. 请理解用户查询的语义，不要只做简单的关键词匹配
2. 返回格式必须是书签标题列表，每行一个标题
3. 不要返回任何解释或其他文本
4. 如果没有相关的书签，返回空白
5. 只返回与查询最相关的书签标题，不相关的不要返回
6. 只能从上面的书签列表中选择，不要生成新的标题

示例返回格式：
书签标题1
书签标题2

请直接返回书签标题列表：`;

      console.log('发送到API的提示词:', prompt);

      // 移除显示提示词的调试代码
      const response = await fetch('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json',
          'X-DashScope-SSE': 'disable'
        },
        body: JSON.stringify({
          model: model,
          input: {
            messages: [
              {
                role: 'user',
                content: prompt
              }
            ]
          }
        })
      });

      const data = await response.json();
      console.log('API响应:', data);
      
      if (!response.ok) {
        console.error('API调用失败:', data);
        const errorMessage = data.message || data.error || JSON.stringify(data);
        console.error('详细错误信息:', errorMessage);
        return [];
      }

      // 更详细地处理通义千问的响应格式
      if (!data.output) {
        console.error('API响应缺少output字段:', data);
        return [];
      }

      const aiResponse = data.output.text || '';
      console.log('AI返回的原始文本:', aiResponse);

      // 移除显示AI响应的调试代码
      if (!aiResponse) {
        console.error('API响应文本为空');
        return [];
      }

      // 解析返回的书签标题列表
      const titles = aiResponse
        .split('\n')
        .map(title => title.trim())
        .filter(title => title);

      // 将AI返回的标题匹配到原始书签
      const aiBookmarks = titles.map(aiTitle => {
        // 尝试在原始书签中找到完全匹配的书签
        const matchedBookmark = bookmarks.find(bookmark => 
          (bookmark.title || bookmark.url).toLowerCase() === aiTitle.toLowerCase()
        );
        
        if (matchedBookmark) {
          // 如果找到匹配的书签，使用原始书签的信息
          return {
            ...matchedBookmark,
            isAiResult: true
          };
        }
        
        // 如果没有完全匹配，尝试模糊匹配
        const fuzzyMatch = bookmarks.find(bookmark => 
          (bookmark.title || bookmark.url).toLowerCase().includes(aiTitle.toLowerCase()) ||
          aiTitle.toLowerCase().includes((bookmark.title || bookmark.url).toLowerCase())
        );
        
        if (fuzzyMatch) {
          return {
            ...fuzzyMatch,
            isAiResult: true
          };
        }
        
        return null;
      }).filter(bookmark => bookmark !== null);

      return aiBookmarks;
    } catch (error) {
      console.error('语义搜索失败:', error);
      // 添加更友好的错误信息处理
      const errorMessage = error.message || '未知错误';
      console.error('详细错误信息:', errorMessage);
      return [];
    }
  }

  // 显示AI搜索状态
  function showAiSearchStatus() {
    let statusElement = document.querySelector('.ai-search-status');
    if (!statusElement) {
      statusElement = document.createElement('div');
      statusElement.className = 'ai-search-status';
      
      // 创建动画容器
      const spinnerContainer = document.createElement('div');
      spinnerContainer.className = 'ai-spinner';
      
      // 添加旋转光环
      const spinnerRing = document.createElement('div');
      spinnerRing.className = 'ai-spinner-ring';
      spinnerContainer.appendChild(spinnerRing);
      
      // 添加文字
      const text = document.createElement('span');
      text.textContent = 'AI正在分析书签内容...';
      
      statusElement.appendChild(spinnerContainer);
      statusElement.appendChild(text);
      bookmarksList.appendChild(statusElement);
    }
    statusElement.style.display = 'flex';
  }

  // 隐藏AI搜索状态
  function hideAiSearchStatus() {
    const statusElement = document.querySelector('.ai-search-status');
    if (statusElement) {
      statusElement.remove();
    }
  }

  // 修改书签项的事件监听逻辑
  function renderBookmarks(bookmarks, isSemanticResults = false) {
    bookmarks.forEach(bookmark => {
      const bookmarkItem = document.createElement('div');
      bookmarkItem.className = 'bookmark-item';
      if (isSemanticResults) {
        bookmarkItem.classList.add('ai-result');
      }
      bookmarkItem.dataset.url = bookmark.url;
      
      // 预加载favicon
      const faviconImg = preloadFavicon(bookmark);
      
      bookmarkItem.innerHTML = `
        <img class="bookmark-favicon" src="${getFaviconUrl(bookmark)}" alt="favicon">
        <span class="bookmark-title">${bookmark.title || bookmark.url}</span>
      `;

      // 鼠标进入时预览
      bookmarkItem.addEventListener('mouseenter', () => {
        if (activeBookmarkItem) {
          activeBookmarkItem.classList.remove('active');
        }
        activeBookmarkItem = bookmarkItem;
        bookmarkItem.classList.add('active');
        handlePreview(bookmark.url);
      });

      // 添加点击事件，在新标签页打开
      bookmarkItem.addEventListener('click', () => {
        chrome.tabs.create({
          url: bookmark.url,
          active: true
        });
      });

      bookmarksList.appendChild(bookmarkItem);
    });
    
    updateResultsCount();
  }

  // 添加搜索输入事件监听
  let keywordSearchTimeout = null;
  let aiSearchTimeout = null;
  searchInput.addEventListener('input', function() {
    const query = this.value.trim();
    
    // 清除之前的定时器
    clearTimeout(keywordSearchTimeout);
    clearTimeout(aiSearchTimeout);
    
    // 清除AI搜索结果
    clearAiResults();
    
    // 使用较短的延时处理关键词搜索
    keywordSearchTimeout = setTimeout(() => {
      searchBookmarks(query, false);
      saveState();
    }, 300);

    // 使用较长的延时处理AI搜索
    aiSearchTimeout = setTimeout(() => {
      searchBookmarks(query, true);
    }, 1000);
  });

  // 初始化
  restoreState();
}); 